package com.cjm.one.custom.apps.controller;

import cn.hutool.core.util.RandomUtil;
import com.cjm.one.common.annotation.IgnoreTenantForAdmin;
import com.cjm.one.common.constant.RedisConstants;
import com.cjm.one.common.exception.GlobalException;
import com.cjm.one.common.result.Result;
import com.cjm.one.common.result.ResultCodeEnum;
import com.cjm.one.common.utils.AuthCustomerContextHolder;
import com.cjm.one.custom.service.CustomerInfoService;
import com.cjm.one.custom.service.MailService;
import com.cjm.one.model.base.TokenVo;
import com.cjm.one.model.custom.entity.CustomerInfo;
import com.cjm.one.model.custom.vo.CustomerInfoVo;
import com.cjm.one.model.system.vo.LoginVo;
import com.cjm.one.security.annotation.Within;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Tag(name = "客户登录管理")
@RequestMapping("/app/customer")
public class AuthLoginController {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CustomerInfoService customerInfoService;
    @Resource
    private MailService mailUtil;

    @GetMapping("/emailCode")
    @Operation(summary = "发送邮箱验证码")
    public Result<Boolean> emailCode(@RequestParam("email") String email)  {
        String redisKey = RedisConstants.EMAIL_LIMIT_EXPIRE + email;
        if(redisTemplate.hasKey(redisKey)){
            throw new GlobalException(ResultCodeEnum.EMAIL_LIMIT_EXPIRED);
        }
        redisTemplate.opsForValue().set(redisKey, email, 1, TimeUnit.MINUTES);

        // 设置邮件正文内容，第一个参数是 HTML 格式的文本内容，第二个参数为 true 表示内容是 HTML 格式
        String numbers = RandomUtil.randomNumbers(6);
        redisTemplate.opsForValue().set(RedisConstants.CAPTCHA_SMSCODE_KEY_EXPIRE + email, numbers,RedisConstants.CAPTCHA_SMS_CODE_EXPIRE, TimeUnit.SECONDS);

        String htmlContent = """
    <div style="max-width: 600px; margin: 20px auto; padding: 30px; border-radius: 10px; background: #f8f9fa; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
        <div style="text-align: center; margin-bottom: 25px;">
            <img src="https://your-company-logo.com/logo.png" alt="Company Logo" style="height: 50px;">
            <h2 style="color: #2c3e50; margin: 15px 0;">欢迎使用广西民族师范学院陈积明的邮件创建功能</h2>
        </div>
        
        <div style="background: white; padding: 25px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
            <p style="color: #34495e; font-size: 16px; margin: 0 0 15px;">您的验证码为：</p>
            <div style="background: #f0f4f8; padding: 15px; border-radius: 6px; text-align: center; margin-bottom: 20px;">
                <span style="font-size: 28px; font-weight: bold; color: #2980b9; letter-spacing: 3px;">%s</span>
            </div>
            
            <p style="color: #7f8c8d; font-size: 14px; margin: 10px 0;">
                ⏰ 有效期：<strong style="color: #e74c3c;">5分钟</strong><br>
                🔒 安全提示：请勿向任何人泄露此验证码
            </p>
        </div>
        
        <div style="margin-top: 25px; text-align: center; color: #95a5a6; font-size: 12px;">
            <p>此为系统邮件，请勿直接回复<br>
            如有疑问，请联系 <a href="mailto:support@company.com" style="color: #3498db; text-decoration: none;">客服支持</a></p>
            <p style="margin-top: 10px;">© 2024 广西民族师范学院陈积明 版权所有</p>
        </div>
    </div>
    """.formatted(numbers);
        try {
            mailUtil.sendHtmlMail(email, "Hi,你的验证码已经送达验！", htmlContent);
        }catch (MessagingException e) {
            throw new GlobalException(ResultCodeEnum.EMAIL_SEND_ERROR);
        }

        return Result.ok(true);
    }

    @GetMapping("/checkEmail/Code")
    @Operation(summary = "检查邮箱验证码")
    public Result<Boolean> checkEmailCode(@RequestParam("email") String email,@RequestParam("code") String code){

        String codeData = (String)redisTemplate.opsForValue().get(RedisConstants.CAPTCHA_SMSCODE_KEY_EXPIRE + email);
        if(codeData == null ){
            throw new GlobalException(ResultCodeEnum.EMAIL_CODE_EXPIRED);
        }
        if(!codeData.equals(code)){
            throw new GlobalException(ResultCodeEnum.EMAIL_CODE_MISMATCH);
        }
        return Result.ok(true);
    }

    @GetMapping("/byEmail")
    @Operation(summary = "通过邮箱查询客户")
    @IgnoreTenantForAdmin
    @Within
    public Result<CustomerInfo> byEmail(@RequestParam("email") String email)  {
        return Result.ok(customerInfoService.getByEmail(email));
    }
    @GetMapping("/byPhone")
    @Operation(summary = "通过电话查询客户")
    public Result<CustomerInfo> byPhone(@RequestParam("phone") String phone)  {
        return Result.ok(customerInfoService.getByPhone(phone));
    }
    @PostMapping("/login")
    @Operation(summary = "客户登录")
    public Result<TokenVo> login(@RequestBody LoginVo loginVo)  {
        return Result.ok(customerInfoService.login(loginVo));
    }


    @GetMapping("/userInfo")
    @Operation(summary = "获取用户信息")
    public Result<CustomerInfoVo> userInfo()  {
        log.info("用户信息");
        CustomerInfo authContextCustomer = AuthCustomerContextHolder.getAuthContextCustomer();


        if(authContextCustomer == null){
            throw new GlobalException(ResultCodeEnum.AUTHENTICATION_ERROR);
        }
        CustomerInfoVo customerInfoVo = new CustomerInfoVo();
        BeanUtils.copyProperties(authContextCustomer, customerInfoVo);
        customerInfoVo.setIsSetPassword(authContextCustomer.getPassword() != null);
        customerInfoVo.setIsSetPayPassword(authContextCustomer.getPayPassword() != null);
        return Result.ok(customerInfoVo);
    }




}
